package com.example.myapplication2.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "TodoApp.db";
    private static final int DATABASE_VERSION = 2;

    // 用户表
    public static final String TABLE_USERS = "users";
    public static final String COLUMN_ID = "id";
    public static final String COLUMN_USERNAME = "username";
    public static final String COLUMN_PASSWORD = "password";

    // 任务表
    public static final String TABLE_TASKS = "tasks";
    public static final String COLUMN_TASK_NUMBER = "task_number";
    public static final String COLUMN_TITLE = "title";
    public static final String COLUMN_DESCRIPTION = "description";
    public static final String COLUMN_REMINDER_DATE = "reminder_date";
    public static final String COLUMN_REMINDER_TIME = "reminder_time";
    public static final String COLUMN_PRIORITY = "priority";
    public static final String COLUMN_IS_COMPLETED = "is_completed";
    public static final String COLUMN_CREATE_TIME = "create_time";
    public static final String COLUMN_USER_ID = "user_id";

    // 创建用户表的SQL语句
    private static final String CREATE_TABLE_USERS = 
        "CREATE TABLE " + TABLE_USERS + " (" +
        COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
        COLUMN_USERNAME + " TEXT UNIQUE NOT NULL, " +
        COLUMN_PASSWORD + " TEXT NOT NULL)";

    // 创建任务表的SQL语句
    private static final String CREATE_TABLE_TASKS = 
        "CREATE TABLE " + TABLE_TASKS + " (" +
        COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
        COLUMN_TASK_NUMBER + " TEXT NOT NULL, " +
        COLUMN_TITLE + " TEXT NOT NULL, " +
        COLUMN_DESCRIPTION + " TEXT, " +
        COLUMN_REMINDER_DATE + " TEXT NOT NULL, " +
        COLUMN_REMINDER_TIME + " TEXT, " +
        COLUMN_PRIORITY + " INTEGER DEFAULT 0, " +
        COLUMN_IS_COMPLETED + " INTEGER DEFAULT -1, " +
        COLUMN_CREATE_TIME + " DATETIME DEFAULT CURRENT_TIMESTAMP, " +
        COLUMN_USER_ID + " INTEGER NOT NULL, " +
        "FOREIGN KEY(" + COLUMN_USER_ID + ") REFERENCES " +
        TABLE_USERS + "(" + COLUMN_ID + ") ON DELETE CASCADE)";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_USERS);
        db.execSQL(CREATE_TABLE_TASKS);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_TASKS);
        onCreate(db);
    }
} 